package com.arpa.ntocc.common.service.impl;

import com.alicp.jetcache.Cache;
import com.alicp.jetcache.CacheGetResult;
import com.alicp.jetcache.CacheResult;
import com.alicp.jetcache.anno.CreateCache;
import com.arpa.ntocc.common.domain.entity.Client;
import com.arpa.ntocc.common.mapper.ClientMapper;
import com.arpa.ntocc.common.service.IClientService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 客户端 服务实现类
 * </p>
 *
 * @author LEO
 * @since 2019-08-12
 */
@Service
@Log4j2
public class ClientServiceImpl extends ServiceImpl<ClientMapper, Client> implements IClientService {

    @CreateCache(name = "client:")
    private Cache<String, Client> clientCache;
    /**
     * 校验clientId和clientSecret是否正确
     *
     * @param clientId
     * @param clientSecret
     * @return
     */
    @Override
    public boolean verificationIdAndSecret(String clientId, String clientSecret) {
        return getClient(clientId,clientSecret)!=null;
    }


    @Override
    public Client getClient(String clientId, String clientSecret) {
        CacheGetResult<Client> clientCacheGetResult = clientCache.GET(clientId + ":" + clientSecret);
        if (clientCacheGetResult.isSuccess()) {
            return clientCacheGetResult.getValue();
        }else {
            Client client = baseMapper.selectOne(new QueryWrapper<Client>().lambda().eq(Client::getClientId,clientId).eq(Client::getClientSecret, clientSecret));
            if(client!=null) {
                CacheResult cacheResult  = clientCache.PUT(clientId + ":" + clientSecret, client);
                if(cacheResult.isSuccess()) {
                    log.error("Client信息缓存失败：{}", cacheResult.getMessage());
                }
                return client;
            }
            return null;
        }
    }
}
